<template>
  <el-dialog v-model="show" :title="title" width="20%" align-center @close="handleClose">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto" class="demo-ruleForm" status-icon>
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="工艺名称" prop="name">
            <el-input v-model="ruleForm.name" placeholder="请输入工艺名称" style="width: 200px;" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="工艺描述" prop="remark">
            <el-input v-model="ruleForm.remark" placeholder="请输入工艺描述" style="width: 200px;" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="工艺价格" prop="price">
            <el-input v-model="ruleForm.price" type="number" @input="(val: any) => ruleForm.price = val < 0 ? 0 : val"
              placeholder="请输入工艺的价格" style="width: 200px;" />
          </el-form-item>
        </el-col> -->
        <el-col :span="24">
          <el-form-item v-for="(item, index) in ruleForm.joinList" :key="item.type" :label="`${item.label}的价格`"
            :prop="`joinList.${index}.price`" :rules="[
              { required: true, message: `请输入${item.label}的价格`, trigger: 'blur' }
            ]">
            <el-input v-model="item.price" type="number" @input="(val: any) => item.price = val < 0 ? 0 : val"
              :placeholder="`请输入${item.label}的价格`" style="width: 200px;" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="排序" prop="sort">
            <el-input v-model="ruleForm.sort" type="number" placeholder="请输入排序" style="width: 200px;" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="图片" prop="imageUrls">
            <el-upload ref="designSketchRef" :limit="2" drag :action="uploadImgUrl" :headers="headers" multiple
              :auto-upload="true" list-type="picture-card" :file-list="fileList" :on-success="handleDesignSketchSuccess"
              :before-upload="beforedeSignSketchUpload">
              <el-icon>
                <Plus />
              </el-icon>

              <template #file="{ file }">
                <div>
                  <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                  <span class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                      <el-icon><zoom-in /></el-icon>
                    </span>
                    <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                      <el-icon>
                        <Delete />
                      </el-icon>
                    </span>
                  </span>
                </div>
              </template>
            </el-upload>

            <el-dialog v-model="dialogVisible">
              <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" v-loading="loading" @click="handleSubmit(ruleFormRef)">{{ btnTitle }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { addNewProcess, updateProcess } from '@/api/accessoryManagement/index'
import { globalHeaders } from "@/utils/request";
import { Delete, Plus, ZoomIn } from '@element-plus/icons-vue'
import type { FormInstance, UploadProps, UploadFile } from 'element-plus'

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const props = defineProps(['visible', 'initList']);
const emits = defineEmits(['submit', 'close']);

const show = ref(false);
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(baseUrl + "/resource/oss/upload");
const headers = ref(globalHeaders);
const componentTypeList: any = ref([])
const btnTitle = ref('新 增');
const title = ref('新增工艺')

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<any>({
  name: '',
  remark: '',
  sort: '',
  imageUrls: [],
  joinList: []
})
const fileTypes = ['image/png', 'image/jpeg']

const rules = reactive<any>({
  name: [
    { required: true, message: '请输入工艺名称', trigger: 'blur' },
  ],
  remark: [
    { required: true, message: '请输入工艺描述', trigger: 'blur' },
  ],
  imageUrls: [
    { required: true, message: '请上传展示图', trigger: ['change', 'blur'] },
  ],
})

const loading = ref(false)
const designSketchRef = ref()
const fileList = ref<UploadFile[]>([])

watch(() => props.visible, async (newValue) => {
  show.value = newValue
  if (newValue) {
    if (props.initList?.id) {
      ruleForm.name = props.initList?.detailsObj?.name
      ruleForm.remark = props.initList?.detailsObj?.remark
      ruleForm.price = props.initList?.detailsObj?.price
      ruleForm.sort = props.initList?.detailsObj?.sort
      ruleForm.imageUrls = props.initList?.detailsObj?.imageUrl.split(',')
      fileList.value = ruleForm.imageUrls.map((url: string) => ({
        name: url.split('/').pop() || 'image',
        url: url,
        uid: url,
      }))
      ruleForm.joinList = props.initList?.volume_interval.map((item: any) => {
        return {
          label: item.label,
          type: item.value,
          price: props.initList?.detailsObj?.priceList.find((priceItem: any) => priceItem.type === item.value)?.price,
        }
      })
      title.value = '修改工艺'
      btnTitle.value = '修 改'

    } else {
      title.value = '新增工艺'
      btnTitle.value = '新 增'
      ruleForm.joinList = props.initList?.volume_interval.map((item: any) => {
        return {
          label: item.label,
          type: item.value,
          price: null,
        }
      })
    }
  }
}, { deep: true });
const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const list = JSON.parse(JSON.stringify(ruleForm.joinList))
      let quert = {
        ...ruleForm,
        imageUrl: ruleForm.imageUrls.join(','),
        priceList: list.map((item: any) => {
          return {
            type: item.type,
            price: item.price,
          }
        }),
      }

      if (props.initList?.id) {
        quert.id = props.initList?.id
        try {
          loading.value = true;
          await updateProcess(quert)
          proxy?.$modal.msgSuccess('修改成功');
          emits('submit', true);
          loading.value = false;

          handleClose();
        } catch (error) {
          loading.value = false;
        }
      } else {
        try {
          loading.value = true;
          await addNewProcess(quert)
          proxy?.$modal.msgSuccess('新增成功');
          emits('submit', true);
          loading.value = false;

          handleClose();
        } catch (error) {
          loading.value = false;
        }
      }

    } else {
      console.log('error submit!', fields)
    }
  })
}

const handleRemove = (file: any) => {
  let url = ''
  if (file.url) {
    url = file.url;
  } else {
    url = file.response.data.url;
  }
  ruleForm.imageUrls = ruleForm.imageUrls.filter((imageUrl: string) => imageUrl !== url);
  designSketchRef.value.handleRemove(file)
};

const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!
  dialogVisible.value = true
}

/**
* 上传配件展示图格式的判定
*/
const beforedeSignSketchUpload: UploadProps['beforeUpload'] = (rawFile) => {
  console.log(rawFile)
  if (!fileTypes.includes(rawFile.type)) {
    ElMessage.error('请上传jpg/png格式的图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error('图片不可超过 5MB!')
    return false
  }
  return true
};

/**
* 上传配件展示图 成功回调
*/
const handleDesignSketchSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  ruleForm.imageUrls.push(response.data.url)
};
const handleClose = () => {
  ruleFormRef.value?.resetFields();
  designSketchRef.value?.clearFiles();
  ruleForm.name = ''
  ruleForm.remark = ''
  ruleForm.price = ''
  ruleForm.sort = ''
  ruleForm.imageUrls = []
  emits('close');
};

onMounted(() => {
})
</script>

<style lang="scss" scoped>
.exhibition {
  width: 100%;
  max-height: 400px;
  overflow-y: auto;
  padding: 5px;

  .colourContainer {
    cursor: pointer;

    &_list {
      display: flex;
      align-items: center;
      height: 100%;
      overflow-x: auto;
      margin-top: 6px;
    }

    &_item {
      margin-right: 10px;
      width: 100px;

      .el-image {
        border-radius: 12px;
      }

      &_name {
        text-align: center;
        width: 100%;
      }
    }

  }

  &_container {
    margin-top: 10px;
    display: flex;

    >div {
      flex: 1;
    }
  }
}

::v-deep .el-upload-dragger {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>